package com.yshkj.payment;

import com.yshkj.payment.dto.LoginDto;
import com.yshkj.payment.entity.UserAccount;
import com.yshkj.payment.utils.HttpServletResponseUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理用户登录,返回Json数据
 * Created by 唐旭 on 2016/9/28.
 */
public class LoginHandler implements AuthenticationFailureHandler, AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        LoginDto loginSuccessDto = new LoginDto();
        loginSuccessDto.setMessage("用户名或密码错误");
        HttpServletResponseUtils.writeObject2Json(loginSuccessDto, httpServletResponse);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse, Authentication authentication)
            throws IOException, ServletException {
        UserAccount principal = (UserAccount) authentication.getPrincipal();
        LoginDto loginSuccessDto = new LoginDto(principal.getUsername());
        HttpServletResponseUtils.writeObject2Json(loginSuccessDto, httpServletResponse);
    }
}
